package com.dyz.leetcode._02_string;

import java.util.ArrayList;
import java.util.List;

public class _557_reverseWords {
    public String reverseWords(String s) {
        int n = s.length();
        if (n<=2){return s;}
        List<String> list = new ArrayList<>();
        String[] s1 = s.split(" ");
        for(String ss : s1){
            char[] chars = ss.toCharArray();
            revers(chars, 0, chars.length-1);
            list.add(new String(chars));
        }
        return String.join(" ", list);
    }

    public String reverseWords1(String s) {
       char[] chars = s.toCharArray();
       int n = chars.length;
       int left = 0;
       while (left<n){
           if(chars[left]!=' '){
               int right = left;
               while (right+1<n && chars[right+1]!=' '){right++;}
               revers(chars,left,right);
               left = right+1;

           }else {
               left++;
           }
       }
       return new String(chars);
    }

    private void revers(char[] chars, int start, int end){
        int left = start;
        int right = end;
        while (left<=right){
            char temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;
            left++;
            right--;
        }
    }
}
